package com.jiyinit.web.core.mobile.controller;

import com.jiyinit.core.framework.base.entity.ResponseDto;
import com.jiyinit.core.framework.base.util.JsonEntityTransform;
import com.jiyinit.core.framework.base.util.LogUtil;
import com.jiyinit.web.core.business.dto.BulewallRequest;
import com.jiyinit.web.core.business.dto.MemoireRequest;
import com.jiyinit.web.core.business.service.MemoireServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by lr on 2018/1/4.
 */
@Controller
@RequestMapping("mobile/memoire")
public class MmemoireController {

    @Resource(name = "core.memoireService")
    MemoireServiceImpl memoireService;

    /**
     * 日志对象
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(MmemoireController.class);

    @RequestMapping("add")
    public ResponseEntity<ResponseDto> add(HttpServletRequest request){
        MemoireRequest memoireRequest = getJsonToTaskRequest(request);
        if (memoireRequest.getContent() == null) {
            return new ResponseEntity<>(ResponseDto.responseFail("内容不能为空"), HttpStatus.OK);
        }

        int num = memoireService.add(memoireRequest);
        if(num > 0)
            return new ResponseEntity<>( ResponseDto.responseOK(""), HttpStatus.OK);
        return new ResponseEntity<>( ResponseDto.responseFail("新建失败！"), HttpStatus.OK);
    }

    @RequestMapping("delete")
    public ResponseEntity<ResponseDto> delete(HttpServletRequest request){
        MemoireRequest memoireRequest = getJsonToTaskRequest(request);
        if (memoireRequest.getMemoireId() == null) {
            return new ResponseEntity<>(ResponseDto.responseFail("Id不能为空"), HttpStatus.OK);
        }

        int num = memoireService.delete(memoireRequest.getMemoireId(),memoireRequest.getUserId());
        if(num > 0)
            return new ResponseEntity<>( ResponseDto.responseOK(""), HttpStatus.OK);
        return new ResponseEntity<>( ResponseDto.responseFail("删除失败！"), HttpStatus.OK);
    }

    private MemoireRequest getJsonToTaskRequest(HttpServletRequest request){
        String content = (String) request.getAttribute("request_json");
        String logJson = request.getParameter("request_json");
        LogUtil.info(LOGGER, "logJson:{}", logJson);
        MemoireRequest memoireRequest = (MemoireRequest) JsonEntityTransform.json2Object(logJson, MemoireRequest.class);
        return memoireRequest;
    }
}
